 //
//  PlayHistoryWordsManager.m
//  TTKanKan
//
//  Created by 龚丁禧 on 15/12/2.
//  Copyright © 2015年 xiangchao. All rights reserved.
//

#import "PlayHistoryWordsManager.h"

static NSString *const TTKK_SEARCH_HISTORY_WORDS = @"SEARCH_HISTORY_WORDS";
static const NSUInteger HISTORY_KEY_WORDS_NUM = 100;

@interface PlayHistoryWordsManager(){
    NSArray * _searchHistoryWords;
}

@end

@implementation PlayHistoryWordsManager

singleton_implementation(PlayHistoryWordsManager)

-(NSArray *)searchHistoryWords
{
    if ([_searchHistoryWords count] == 0) {
        NSUserDefaults * ud = [NSUserDefaults standardUserDefaults];
        _searchHistoryWords = [NSArray arrayWithArray: [ud objectForKey: TTKK_SEARCH_HISTORY_WORDS]];
    }
    
    return _searchHistoryWords;
}

-(void)addSearchHistoryWord: (NSString *) word
{
    int index;
    
    if (word == nil) {
        return;
    }
    //查找该搜索词是否出现过
    for (index = 0; index < [_searchHistoryWords count] ; index++) {
        if ([word isEqualToString: [_searchHistoryWords objectAtIndex: index]]) {
            break;
        }
    }
    
    NSMutableArray *editArr = [NSMutableArray arrayWithArray:_searchHistoryWords ];
    //该搜索词已经出现过，将位置移到第一个，表示最新搜索的一个词
    if (index < [_searchHistoryWords count ]) {
        [editArr removeObjectAtIndex: index];
        [editArr insertObject: word atIndex: 0];
    } else {
        // 添加没有出现过的搜索词到第一个
        [editArr insertObject:word atIndex: 0];
        
        if ([editArr count] > HISTORY_KEY_WORDS_NUM) {
            [editArr removeLastObject];
        }
    }

    _searchHistoryWords = editArr;
    NSUserDefaults * ud = [NSUserDefaults standardUserDefaults];
    [ud setObject: _searchHistoryWords forKey: TTKK_SEARCH_HISTORY_WORDS];
}

-(void)removeSearchHistoryWord:(NSString *) word
{
    int index;
    //查找该搜索词是否出现过
    for (index = 0; index < [_searchHistoryWords count] ; index++) {
        if ([word isEqualToString: [_searchHistoryWords objectAtIndex: index]]) {
            break;
        }
    }
    
    NSMutableArray *editArr = [NSMutableArray arrayWithArray:_searchHistoryWords ];
    //该搜索词已经出现过，删除该搜索词
    if (index < [_searchHistoryWords count ]) {
        [editArr removeObjectAtIndex: index];
    }
    
    _searchHistoryWords = editArr;
    NSUserDefaults * ud = [NSUserDefaults standardUserDefaults];
    [ud setObject: _searchHistoryWords forKey: TTKK_SEARCH_HISTORY_WORDS];
}

@end
